/**
 * 
 */
package evance.server.spring.core.interceptor;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;

/**
 * @author BaoVuong
 *
 */
public class ExecuteTimeInterceptor implements Ordered {
	private static Logger log = Logger.getLogger(ExecuteTimeInterceptor.class);
	private int order = -2147483648;
	private List<ExecuteTimeStore> listExecuteTimeStore;

	public ExecuteTimeInterceptor() {
		this.listExecuteTimeStore = new ArrayList<ExecuteTimeStore>();
		this.listExecuteTimeStore.add(new Log4jExecuteTimeStore());
	}

	public List<ExecuteTimeStore> getListExecuteTimeStore() {
		return this.listExecuteTimeStore;
	}

	public void setListExecuteTimeStore(
			List<ExecuteTimeStore> listExecuteTimeStore) {
		this.listExecuteTimeStore = listExecuteTimeStore;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	public int getOrder() {
		return this.order;
	}

	public Object checkExecuteTime(ProceedingJoinPoint joinPoint)
			throws Throwable {
		Date startTime = null;
		Date endTime = null;
		ExecuteTimeStore.ExecuteTimeInfo exeTimeInfo;
		Object localObject1;
		try {
			startTime = new Date();
			localObject1 = joinPoint.proceed();
		} finally {
			endTime = new Date();
			long durationMilisecond = endTime.getTime() - startTime.getTime();
			exeTimeInfo = new ExecuteTimeStore.ExecuteTimeInfo(
					((MethodSignature) joinPoint.getSignature()).getMethod(),
					startTime, endTime, durationMilisecond);
			for (ExecuteTimeStore store : this.listExecuteTimeStore)
				try {
					store.add(exeTimeInfo);
				} catch (Exception e) {
					log.error("can't write execute time to sotre, cause: "
							+ e.getClass().getName() + ", " + e.getMessage());
				}
		}
		return localObject1;
	}

}
